import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import { clearResultAction, searchAction } from '@/store/action/search';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';
import { useDispatch } from 'react-redux';
import { InfiniteScroll } from 'antd-mobile';

export default function Result() {
  const location = useLocation<{ searchKey: string }>();
  const dispatch = useDispatch();
  const searchKey = location.state.searchKey;
  const pageRef = useRef(0);
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    // dispatch(searchAction({ q: searchKey }));
    return () => {
      dispatch(clearResultAction());
    };
  }, [dispatch]);

  const { resultList } = useAppSelector((state) => state.search);
  const handleLoadMore = async () => {
    // console.log(pageRef.current * 10 <= resultList.length);
    // console.log(pageRef.current * 10, resultList.length);
    if (pageRef.current * 10 > resultList.length) {
      setHasMore(false);
    } else {
      pageRef.current = pageRef.current + 1;
      await dispatch(
        searchAction({ q: searchKey, page: pageRef.current, per_page: 10 })
      );
    }
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {!!resultList.length &&
          resultList.map((item, index) => (
            <ArticleItem article={item} key={index} />
          ))}
      </div>

      <InfiniteScroll loadMore={() => handleLoadMore()} hasMore={hasMore} />
    </div>
  );
}
